package com.ykdl.member.kid.util;

import oauth.signpost.http.HttpParameters;

import org.json.JSONException;
import org.json.JSONObject;

import com.ykdl.member.base.QLog;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.beans.AnonymousBean;
import com.ykdl.member.kid.beans.HomeMessageCount;
import com.ykdl.member.kid.beans.RegisterPhonebean;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;
import net.wxxr.http.util.Constants;
import android.app.Activity;
import android.content.Context;

public class RequestAsAccessTokenUtil {

	private static RequestAsAccessTokenUtil instance;
	private static Context mContext;
	boolean isExpired = false;

	private RequestAsAccessTokenUtil() {
	};

	public synchronized static RequestAsAccessTokenUtil getInstance(
			Context context) {
		mContext = context;
		if (instance == null) {
			instance = new RequestAsAccessTokenUtil();
		}
		return instance;
	}

	public void  refreshTokenRequest(final HttpBaseRequest request,
			final ITag tag, final Class clazz) {
		//避免多线程并发时，出现数据同时被修改的情况
		synchronized (RequestAsAccessTokenUtil.class) {
			// 刷新access_token
			final String url = KidConfig.BASE_TEST_SERVER + "oauth2/access_token";
			HttpParameters bodyParams = new HttpParameters();
			bodyParams.put("client_id", Constants.CLIENT_ID);
			bodyParams.put("client_secret", Constants.CLIENT_SECRET);
			bodyParams.put("grant_type", "refresh_token");
			AccessTokenKeeper keeper = new AccessTokenKeeper(mContext);
			bodyParams.put("token", keeper.getRefresh_token());
			final HttpBaseRequest refresh_request = Wxxr.getInstance()
					.postBaseRequest(url, bodyParams, null);
			TaskManager.startHttpRequest(refresh_request,
					new RefreshAccessTokenTag(request, tag, clazz), null);
		}
		
	}

	class RefreshAccessTokenTag implements ITag {
		private HttpBaseRequest request;
		private ITag tag;
		private Class clazz;

		public RefreshAccessTokenTag(HttpBaseRequest request, ITag tag,
				Class clazz) {
			this.request = request;
			this.tag = tag;
			this.clazz = clazz;
		}

		@Override
		public void refreshUI(Object t, DataState ds) {
			// 获得新的access_token并保存起来
			final AccessTokenKeeper keeper = new AccessTokenKeeper(mContext);
			AnonymousBean anonyMousBean = null;
			RegisterPhonebean registerBean = null;
			try {
				final JSONObject jo = new JSONObject(t.toString());

				if (keeper.getmisAnonymous()) {// 匿名用户

					anonyMousBean = new AnonymousBean(
							jo.getString("anonymous_id"),
							jo.getString("anonymous_token"),
							jo.getString("created_time"),
							jo.getString("display_name"), jo.getString("desc"),
							jo.getString("error"));

					keeper.keepAnonymousToken(mContext, anonyMousBean);

				} else { // 注册用户
					registerBean = new RegisterPhonebean(
							jo.getString("access_token"),
							jo.getString("actor_id"),
							jo.has("actor_type") == true ? jo
									.getString("actor_type") : null,
							(float) jo.getDouble("expires_in"),
							jo.getString("refresh_token"),
							jo.has("desc") == true ? jo.getString("desc")
									: null,
							jo.has("error") == true ? jo.getString("error")
									: null);
					keeper.keepAccessToken(mContext, registerBean);
				}

				// refresh_token 重新请求数据
				TaskManager.startHttpRequest(request, tag, clazz);

			} catch (JSONException e) {
				QLog.debug(((Activity) mContext).getClass().getName(),
						e.getMessage());
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			return false;
		}

		@Override
		public void refreshCancel() {
		}

	}
}
